package com.zh.kotlin_mvvm.ui

import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.RecyclerView
import com.github.promeg.pinyinhelper.Pinyin
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.bindAdapter
import com.zh.kotlin_mvvm.R
import com.zh.kotlin_mvvm.databinding.ActivitySortLetterBinding
import com.zh.kotlin_mvvm.pinyin.ExUserInfo
import com.zh.kotlin_mvvm.pinyin.LettersPinyinComparator
import com.zh.kotlin_mvvm.pinyin.PinyinComparator
import com.zh.kotlin_mvvm.view.StickyDecoration
import java.util.Collections

class SortLetterActivity : BaseActivity<ActivitySortLetterBinding>() {

    private val list = mutableListOf(
        "上海",
        "北京",
        "天津",
        "重庆",
        "四川",
        "甘薯",
        "广州",
        "深圳",
        "云南",
        "浙江",
        "飞机",
        "贵州",
        "贵阳",
        "西藏",
        "新疆",
        "金华",
        "厦门",
        "西安",
        "台湾",
        "大连",
        "吉林"
    )
    private var exUserInfo = arrayListOf<ExUserInfo>()
    private var letters = arrayListOf<String>()
    private val adapter by lazy {
        bindAdapter<ExUserInfo>(R.layout.item_list) { holder, item ->
            holder.setText(R.id.tvTitle, item.name)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        viewBinding.apply {
            val exInfos = arrayListOf<ExUserInfo>()
            //不在24个字母中的开头
            val otInfos = arrayListOf<ExUserInfo>()
            for (datum in list) {
                val exUserInfo = ExUserInfo(datum)
                var letter = ""
                try {
                    letter = java.lang.String.valueOf(Pinyin.toPinyin(datum[0])[0])
                    letter = letter.uppercase()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                if (TextUtils.isEmpty(letter) || !isAlpha(letter)) {
                    exUserInfo.sortLetter = "#"
                    otInfos.add(exUserInfo)
                } else {
                    exUserInfo.sortLetter = letter
                    exInfos.add(exUserInfo)
                }
            }
            for (userInfo in exInfos) {
                if (!letters.contains(userInfo.sortLetter))
                    letters.add(userInfo.sortLetter)
            }
            if (otInfos.isNotEmpty()) letters.add("#")
            Collections.sort(letters, LettersPinyinComparator())
            exUserInfo.addAll(exInfos)
            exUserInfo.addAll(otInfos)
            Collections.sort(exUserInfo, PinyinComparator())

            recyclerView.adapter = adapter
            adapter.setNewInstance(exUserInfo)
            recyclerView.addItemDecoration(StickyDecoration(this@SortLetterActivity, object :
                StickyDecoration.DecorationCallback {
                override fun getData(position: Int): String {
                    return adapter.data[position].sortLetter
                }
            }))
            sortView.setOnLetterChangedListener { letter, position ->
                for (i in 0 until adapter.data.size) {
                    val exUserInfo: ExUserInfo = adapter.data[i]
                    if (exUserInfo.sortLetter.equals(letter, false)) {
                        smoothMoveToPosition(recyclerView, i)
                        return@setOnLetterChangedListener
                    }
                }
            }
        }
    }

    //目标项是否在最后一个可见项之后
    private var mShouldScroll = false

    //记录目标项位置
    private var mToPosition = 0

    /**
     * 滑动到指定位置
     */
    private fun smoothMoveToPosition(mRecyclerView: RecyclerView, position: Int) {
        // 第一个可见位置
        val firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0))
        // 最后一个可见位置
        val lastItem =
            mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.childCount - 1))
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前，使用smoothScrollToPosition
            mRecyclerView.smoothScrollToPosition(position)
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后，最后一个可见项之前
            val movePosition = position - firstItem
            if (movePosition >= 0 && movePosition < mRecyclerView.childCount) {
                val top = mRecyclerView.getChildAt(movePosition).top
                // smoothScrollToPosition 不会有效果，此时调用smoothScrollBy来滑动到指定位置
                mRecyclerView.smoothScrollBy(0, top)
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position)
            mToPosition = position
            mShouldScroll = true
        }
    }

    /**
     * 判断是否是字母
     *
     * @param str 传入字符串
     * @return 是字母返回true，否则返回false
     */
    private fun isAlpha(str: String): Boolean {
        return if (TextUtils.isEmpty(str)) false else str.matches("[a-zA-Z]+".toRegex())
    }
}

